package org.jpass.dc.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录过滤器
 * @author Administrator
 *
 */
public class LoginFilter implements Filter {
	private FilterConfig config;

	/** 实现初始化方法 */
	public void init(FilterConfig config) throws ServletException {
		this.config=config;
	}
	
	/** 实现销毁方法 */
	public void destroy() {
		this.config=null;
	}
	
	/** 执行过滤核心方法 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
				throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		HttpServletResponse httpServletResponse = (HttpServletResponse)response;
		HttpSession session=httpServletRequest.getSession(true);
		String requestPath=httpServletRequest.getServletPath();
		String loginPage=config.getInitParameter("loginPage"); //登录请求
		String registerPage=config.getInitParameter("registerPage");  //注册请求
		String imagePage=config.getInitParameter("imagePage"); //验证码请求
		String forgetpassPage=config.getInitParameter("forgetpassPage"); //忘记密码请求
		String updatepassPage=config.getInitParameter("updatepassPage"); //修改密码请求
		String backloginPage=config.getInitParameter("backloginPage"); //后台登陆页面请求
		//String backmainPage=config.getInitParameter("backmainPage"); //后台页面请求
		if(session.getAttribute("user")!=null //是否已登录
				|| requestPath.equals(loginPage) //登录页
				|| requestPath.equals(registerPage) //注册页
				|| requestPath.equals(imagePage) //验证码
				|| requestPath.equals(forgetpassPage) //忘记密码
				|| requestPath.equals(updatepassPage) //修改密码
				|| requestPath.equals(backloginPage) //后台登录页
				//|| requestPath.equals(backmainPage) //后台主页
				){
			chain.doFilter(request, response);
		}else{
			if(requestPath.startsWith("/backstage/")){ //如果请求后台页面则转到后台登录页
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + backloginPage);
			}else{
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + loginPage);
			}
		}
	}

	
}
